package cn.gjxblog.thread.example.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @author gjx
 * @version v1.0
 * @Description
 * @date 2019/7/2 10:39
 */
@Slf4j
public class SemaphoreExample1 {
    private final static  int threadCount = 200;

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();

        //信号量，阻塞线程 ，效果为20个请求并发
        Semaphore semaphore = new Semaphore(20);

        for (int i = 0; i < threadCount; i++) {
            int finalI = i;
            executorService.execute(()->{
                try {
                    semaphore.acquire();
                    test(finalI);
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
        executorService.shutdown();
    }

    public static void test(int finalI) throws InterruptedException {
        Thread.sleep(1000);
        log.info("thread :{}",finalI);
    }
}
